package cn.com.homeyoda.aimate.aihealth.ui.my.family;

import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.ADD_FAMILY_MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.DELETE_REPORT;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.UPDATE_FAMILY_NAME;

import android.annotation.SuppressLint;
import android.app.Application;

import androidx.annotation.NonNull;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.base.BaseModelMVVM;
import com.wzq.mvvmsmart.event.StateLiveData;
import com.wzq.mvvmsmart.utils.KLog;
import com.wzq.mvvmsmart.utils.RxUtils;
import com.wzq.mvvmsmart.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import cn.com.homeyoda.aimate.aihealth.base.BaseViewModel;
import cn.com.homeyoda.aimate.aihealth.bean.BaseResponse2;
import cn.com.homeyoda.aimate.aihealth.bean.BloodPressureBean;
import cn.com.homeyoda.aimate.aihealth.bean.ExaminationReportBean;
import cn.com.homeyoda.aimate.aihealth.bean.FamilyMembersBean;
import cn.com.homeyoda.aimate.aihealth.bean.InspectionScheduleBean;
import cn.com.homeyoda.aimate.aihealth.bean.MessageTitleBean;
import cn.com.homeyoda.aimate.aihealth.bean.PromptUserListBean;
import cn.com.homeyoda.aimate.aihealth.bean.VisualBean;
import cn.com.homeyoda.aimate.aihealth.data.Repository;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class FamilyViewModel extends BaseViewModel<Repository> {

    public StateLiveData<FamilyMembersBean.DataBean> memberData;
    public StateLiveData<List<PromptUserListBean.RowsBean>> promptUserData;

    public StateLiveData<List<MessageTitleBean>> titleData;

    public StateLiveData<List<ExaminationReportBean.RowsBean>> physicalExamData;

    public StateLiveData<InspectionScheduleBean.DataBean> recordData;
    public StateLiveData<List<VisualBean.DataBean>> visualData;
    public StateLiveData<List<BloodPressureBean.DataBean>> bloodPressureData;

    public FamilyViewModel(@NonNull Application application, BaseModelMVVM model) {
        super(application, model);
        memberData = new StateLiveData<>();
        promptUserData = new StateLiveData<>();

        titleData = new StateLiveData<>();

        physicalExamData = new StateLiveData<>();

        recordData = new StateLiveData<>();

        visualData = new StateLiveData<>();

        bloodPressureData = new StateLiveData<>();

    }

    public void getMemberList() {
        model.getFamilyMembers(model.getFamilyId())
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(FamilyViewModel.this)
                .subscribe(new Observer<FamilyMembersBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        memberData.postLoading();
                    }

                    @Override
                    public void onNext(FamilyMembersBean response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            memberData.postValueAndSuccess(response.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        memberData.postError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });
    }

    public void updateFamilyName(String familyName) {
        model.updateFamilyName(model.getFamilyId(), familyName)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(FamilyViewModel.this)
                .subscribe(new Observer<BaseResponse2>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResponse2 response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            LiveEventBus.get(UPDATE_FAMILY_NAME).post(familyName);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });
    }

    public void getPromptUserList() {
        model.getPromptUserList(model.getFamilyId(), model.getDeviceId(), 1, 20)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(FamilyViewModel.this)
                .subscribe(new Observer<PromptUserListBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        promptUserData.postLoading();
                    }

                    @Override
                    public void onNext(PromptUserListBean response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            promptUserData.postValueAndSuccess(response.getRows());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        promptUserData.postError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void addFamilyMember(List<String> faceIds) {
        Observable.fromIterable(faceIds)
                .concatMap(faceId ->
                        model.addFamilyMember(model.getFamilyId(), faceId)
                                .compose(RxUtils.observableToMain())
                                .compose(RxUtils.exceptionTransformer())
                                .doOnSubscribe(disposable -> KLog.d(TAG, "Started request for faceId: " + faceId))
                                .doOnNext(response -> {
                                    if (response.getCode() == 200) {
                                        KLog.d(TAG, "Success for faceId: " + faceId);
                                    } else {
                                        KLog.e("Failed for faceId: " + faceId + ", response code: " + response.getCode());
                                    }
                                })
                                .map(response -> response.getCode() == 200)
                )
                .all(success -> success) // 全部成功才为 true
                .subscribe(
                        allSuccess -> {
                            if (allSuccess) {
                                KLog.d(TAG, "All requests completed successfully");
                            } else {
                                KLog.w(TAG, "Some requests failed");
                            }
                            LiveEventBus.get(ADD_FAMILY_MEMBER).post(allSuccess);
                        },
                        throwable -> {
                            KLog.e("Exception occurred during requests", throwable);
                            LiveEventBus.get(ADD_FAMILY_MEMBER).post(false);
                        }
                );
    }

    public void getTitleData() {
        List<MessageTitleBean> titleBeanList = new ArrayList<>();
        MessageTitleBean titleBean = new MessageTitleBean();
        titleBean.setTitle("健康档案");
        MessageTitleBean titleBean1 = new MessageTitleBean();
        titleBean1.setTitle("心率记录");
        MessageTitleBean titleBean2 = new MessageTitleBean();
        titleBean2.setTitle("血压记录");
        MessageTitleBean titleBean3 = new MessageTitleBean();
        titleBean3.setTitle("血氧记录");
        MessageTitleBean titleBean4 = new MessageTitleBean();
        titleBean4.setTitle("呼吸记录");

        titleBeanList.add(titleBean);
        titleBeanList.add(titleBean1);
        titleBeanList.add(titleBean2);
        titleBeanList.add(titleBean3);
        titleBeanList.add(titleBean4);
        titleData.postValueAndSuccess(titleBeanList);
    }

    public void getPhysicalExamData(String userId,String faceId) {

        model.getExaminationReportList(userId, faceId, 1, 10)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(FamilyViewModel.this)
                .subscribe(new Observer<ExaminationReportBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        physicalExamData.postLoading();
                    }

                    @Override
                    public void onNext(ExaminationReportBean response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            physicalExamData.postValueAndSuccess(response.getRows());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        physicalExamData.postError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });

    }

    public void deleteReport(String id) {

        model.deleteReport(id)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(FamilyViewModel.this)
                .subscribe(new Observer<BaseResponse2>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResponse2 response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            ToastUtils.showShort("健康档案已删除");
                            LiveEventBus.get(DELETE_REPORT).post(true);
                        } else {
                            ToastUtils.showShort(response.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });
    }

    public void getRecordData(String userId) {

        model.inspectinsSchedule(userId)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(FamilyViewModel.this)
                .subscribe(new Observer<InspectionScheduleBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        recordData.postLoading();
                    }

                    @Override
                    public void onNext(InspectionScheduleBean response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            recordData.postValueAndSuccess(response.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        recordData.postError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });

    }

    /**
     * 获取血压记录数据
     */
    public void getBloodPressureRecord(String faceId, String startTime, String endTime, int pageSize) {

        model.getBloodPressureRecord(faceId, "2", startTime, endTime, pageSize, 1)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(FamilyViewModel.this)
                .subscribe(new Observer<BloodPressureBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        bloodPressureData.postLoading();
                    }

                    @Override
                    public void onNext(BloodPressureBean response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            bloodPressureData.postValueAndSuccess(response.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        bloodPressureData.postError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });

    }

    /**
     * 获取记录数据
     * @param faceId 人脸id
     * @param type 1 心率，2 血氧，3 呼吸
     */
    public void getVisualRecord(String faceId, String type, String startTime, String endTime, int pageSize) {

        model.getVisualRecord(faceId, type, startTime, endTime, pageSize, 1)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(FamilyViewModel.this)
                .subscribe(new Observer<VisualBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        visualData.postLoading();
                    }

                    @Override
                    public void onNext(VisualBean response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            visualData.postValueAndSuccess(response.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        visualData.postError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });

    }

}
